# -*- coding: utf-8 -*-
from selenium import webdriver          # 未完工
from lxml import etree
import requests

def analysis(html):
    us = etree.HTML(html).xpath('//*[@id="office-tab-box"]/div/div[1]/div[3]/ul/li/h4/a')
    urls = []
    for u in us:
        url = 'http://ishare.iask.sina.com.cn' + u.xpath('@href')[0]
        urls.append(url)
        print(url)
    return urls

def analysis_pages(path, html):
    imgs = etree.HTML(html).xpath('//*[@id="canvasWrapper"]/div/div/img')
    count = 0
    for img in imgs:
        count += 1

        img_url = img.xpath('@data-src')  # 有的图片的 地址位于 src 中,有的图片地址位于 data-src 中
        if img_url == []:  # 所以，判断当 data-src 中没有内容的时候,换用另一种方法
            img_url = img.xpath('@src')
        imgs = requests.get(img_url[0])  # 对图片网址发出请求

        save_imgs(path, count, imgs)

def save_imgs(path, count, imgs):
    file_name = path + '\\' + str(count) + '.jpg'
    # 保存文件
    try:
        f = open(file_name, 'ab+')              # 打开
        f.write(imgs.content)                   # 写入内容
        f.close()                               # 关闭
    except:
        print("error")

def render(text):
    driver = webdriver.PhantomJS()
    driver.get('http://ishare.iask.sina.com.cn/')
    driver.find_element_by_id("scondition").send_keys(text)
    driver.find_element_by_id("searchBtn").click()

    html = driver.page_source
    urls = analysis(html)
    num = len(urls)

    now_handle = driver.current_window_handle       # 获取当前窗口句柄

    for n in range(1,num+1):
        if n == 4 :
            driver.find_element_by_xpath('//*[@id="office-tab-box"]/div/div[1]/div[3]/ul/li[' + str(n) + ']/h4/a/span').click()
        print(n)

    handles = (driver.window_handles)  # 获取当前窗口句柄集合（列表类型）
    print(handles)
    for handle in handles:  # 切换窗口
        if handle != now_handle:
            print('switch to ', handle)
            driver.switch_to_window(handle)
            try:
                for i in range(15):
                    driver.find_element_by_xpath(
                        '//*[@id="swfPreview"]/div/div[5]/div[2]/div/div[3]/a/p/span[2] | //*[@id="swfPreview"]/div/div[5]/div[2]/div/div[4]/a/p/span[2] | //*[@id="swfPreview"]/div/div[5]/div[2]/div/a/p/span[2]').click()
            except:
                pass
            finally:
                html = driver.page_source
                driver.close()
                analysis_pages('E:\\百度文库下载', html)

    driver.switch_to_window(handles[0])  # 切换回百度窗口
    driver.close()                       # 关闭原窗口

if __name__ == "__main__":
    render('互联网')